package com.agri.service.impl;

import com.agri.entity.User;
import com.agri.mapper.UserMapper;
import com.agri.result.Result;
import com.agri.service.UserAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Result<?> authenticate(String username, String password) {
        User user = userMapper.selectUserWithRolesByUsername(username);
        if (user == null) {
            return Result.fail("用户名或密码错误");
        }

        if (!passwordEncoder.matches(password, user.getPassword())) {
            return Result.fail("用户名或密码错误");
        }

        return Result.success("认证成功");
    }

    @Override
    public User loadUserById(Long userId) {
        return userMapper.selectUserWithRolesById(userId);
    }
}